package com.tianya.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @program: cloud2020
 * @description
 * @author: tianya
 * @create: 2020-06-17 00:09
 **/
@Service
public class PaymentService {

    /**
     * 正常访问
     * @param id
     * @return
     */
    public String paymentInfoOk(Integer id){
        return "线程池： " + Thread.currentThread().getName() +
                "  方法名 paymentInfoOk,id： " + id + " \t" + "O(n_n)O哈哈~~";
    }

    //设置采用超过2秒就采用服务降级
    @HystrixCommand(fallbackMethod = "paymentInfo_TimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")
    })
    public String paymentInfoTimeout(Integer id){
        int timeNumber = 3;
        try {
            TimeUnit.SECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池： " + Thread.currentThread().getName() +
                "  方法名 paymentInfoTimeout,id： " + id + " \t" +
                "O(n_n)O哈哈~~" + "  耗时(秒)：" + timeNumber;
    }

    public String paymentInfo_TimeoutHandler(Integer id){
        return "对不起，8015接口获取异常，该方法为回调函数";
    }

    // 服务熔断
    @HystrixCommand(fallbackMethod = "paymentInfo_Circuit",commandProperties = {
            @HystrixProperty(name="circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "10000"),// 时间窗口期
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "60")// 失败率
            // 加起来就是在10s内的10次请求中如果失败超过6次进入服务熔断
    })
    public String paymentCircuitBreak(Integer id){
        System.out.println("id = " + id);
        if(id < 0){
            throw new RuntimeException("id为负数");
        }else {
            String number = IdUtil.simpleUUID();
            return "服务调用成功，调用序号为： " + number;
        }
    }

    public String paymentInfo_Circuit(Integer id){
        return "由于参数id被调用时多次为负数，该接口暂时被熔断，不提供服务";
    }
}
